package com.sfang.common.util.bean;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 一些自己用的业务工具类
 */
@Data
public class BusUtil {

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    @SafeVarargs
    public static List<Integer> union(List<Integer> ... lists){
        List<Integer> union = new ArrayList<>();
        for (List<Integer> list : lists) {
            if(CollUtil.isNotEmpty(list)){
                union.addAll(list);
            }
        }
        return union;
    }

    public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> keyExtractor) {
        return list.stream().collect(Collectors.toMap(keyExtractor, Function.identity(), (v1, v2) -> v1));
    }

    public static <T, K, V> Map<K, V> listToMap(List<T> list, Function<T, K> keyExtractor, Function<T, V> valueExtractor) {
        return list.stream().collect(Collectors.toMap(keyExtractor, valueExtractor, (v1, v2) -> v1));
    }
}
